package com.cloudcc.mobile.view.activity;


import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cloudcc.cloudframe.bus.BaseEvent;
import com.cloudcc.cloudframe.bus.DynamicEventList;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.util.DateUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.BullXiangGuanDao;
import com.cloudcc.mobile.dao.impl.BullXiangGuanImpl;
import com.cloudcc.mobile.dialog.BullListDialog;
import com.cloudcc.mobile.dialog.MakeTureDialog;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.BullGzlxEntity;
import com.cloudcc.mobile.entity.BullJxsNewJob;
import com.cloudcc.mobile.entity.map.MapLocation;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.ImageUtil;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.photo.Constants;
import com.cloudcc.mobile.util.photo.Util;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.mypage.view.datedialog.DateTimeUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.cloudcc.mobile.R.id.bull_address_tv;
import static com.cloudcc.mobile.R.id.jxs_bull;
import static com.cloudcc.mobile.R.id.md_bull;
import static com.cloudcc.mobile.R.id.qkms_bull;

/**
 * Created by lin on 2017/10/25.
 */

public class BullNewJobActivity extends BaseActivity implements View.OnClickListener, IEventLife, BullListDialog.ChangeListener {

    @Bind(R.id.newjob_back)
    ImageView newjobBack;
    @Bind(R.id.newjob_save)
    Button newjobSave;
    @Bind(jxs_bull)
    TextView jxsBull;
    @Bind(md_bull)
    TextView mdBull;
    @Bind(R.id.bull_job_type)
    TextView bullJobType;
    @Bind(R.id.image1_bull)
    ImageView image1Bull;
    @Bind(R.id.image2_bull)
    ImageView image2Bull;
    @Bind(qkms_bull)
    EditText qkmsBull;
    @Bind(bull_address_tv)
    TextView bullAddressTv;
    @Bind(R.id.bull_address_layout)
    LinearLayout bullAddressLayout;
    @Bind(R.id.start_time)
    Button starttime;
    @Bind(R.id.end_time)
    Button endtime;
    private String zuobiao;
    private String imagename;
    private List<AddImageInfo> imageArray = new ArrayList<AddImageInfo>();
    private List<AddImageInfo> imageArray2 = new ArrayList<AddImageInfo>();
    private List<AddImageInfo> imageArrayAll = new ArrayList<AddImageInfo>();
    private Map<String,String> jsonlist;
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private BullXiangGuanDao bullDao;
    private String jxsId;//选择的经销商id
    private static final int TAKE_PHOTO_1 = 5001;
    private static final int TAKE_PHOTO_2 = 5002;
    private List<BullJxsNewJob> listJxs, listMenD;
    private List<BullGzlxEntity> listGzjl;
    private ImageLoadingListener animateFirstListener = new Util.AnimateFirstDisplayListener();
    private BullListDialog changeDialog;
    private MakeTureDialog makeTureDialog;
    //图片上传
    private DynamicControl dynamicControl = new DynamicControl();
    private boolean haveJxs = false, haveGzlx = false;
    private String isxunjian = "notye";
    public MapLocation currentLoc = new MapLocation();// 位置

    private String mDatime;
    private  String mdid;

    private boolean isSave = false;
    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);

        bullDao = new BullXiangGuanImpl();
        listJxs = new ArrayList<>();
        listMenD = new ArrayList<>();
        changeDialog = new BullListDialog(this, R.style.DialogLoadingTheme,this);
        makeTureDialog = new MakeTureDialog(this, R.style.DialogLoadingTheme);
        register();
        initLocation();
        initLister();
        initdata();
        setTimeStr();
    }

    private void initdata() {
        BeauEventList.BullJxsEvent Event = new BeauEventList.BullJxsEvent();//查询经销商
        bullDao.BullgetJxs("Account", "", "khmc,name", Event);
        BeauEventList.BullGzlxEvent Event2 = new BeauEventList.BullGzlxEvent();//查询工作类型
        String data = "{\"objectApiName\":\"gzjl\",\"fieldApi\":\"gzlx\",\"recordType\":\"\"}";
        bullDao.BullgetGzlx(data, Event2);
    }

    private void initLister() {
        newjobBack.setOnClickListener(this);
        newjobSave.setOnClickListener(this);
        jxsBull.setOnClickListener(this);
        mdBull.setOnClickListener(this);
        bullJobType.setOnClickListener(this);
        image1Bull.setOnClickListener(this);
        image2Bull.setOnClickListener(this);
        starttime.setOnClickListener(this);
        endtime.setOnClickListener(this);
    }

    public void onEventMainThread(BeauEventList.BullJxsEvent event) {

        listJxs = event.getData();
        if (listJxs != null && listJxs.size() != 0) {//查询到经销商
            haveJxs = true;
        } else {//没有查到经销商
            haveJxs = false;
        }
    }

    public void onEventMainThread(BeauEventList.BullMenDianEvent event) {

        listMenD = event.getData();
        if (listMenD != null && listMenD.size() != 0) {//查询到门店
            changeDialog.show();
            changeDialog.setDataMD(listMenD);
        } else {//没有查到门店
            makeTureDialog.show();
            makeTureDialog.setTitle("没有适合的门店");
        }
    }

    public void onEventMainThread(BeauEventList.BullGzlxEvent event) {

        listGzjl = event.getData();
        if (listGzjl != null && listGzjl.size() != 0) {//查询到工作记录
            haveGzlx = true;
        } else {//没有查到工作记录
            haveGzlx = false;
        }
    }


    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_bull_new_job;
    }

    private void initLocation() {
        LocationManager.getInstance().registerListener(mListener);
        LocationManager.getInstance().requestLocal();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public static void bubbleSort(int[] numbers)
    {
        int temp = 0;
        int size = numbers.length;
        for(int i = 0 ; i < size-1; i ++)
        {
            for(int j = 0 ;j < size-1-i ; j++)
            {
                if(numbers[j] > numbers[j+1])  //交换两数位置
                {
                    temp = numbers[j];
                    numbers[j] = numbers[j+1];
                    numbers[j+1] = temp;
                }
            }
        }
    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.newjob_back:// 返回
                finish();
                break;
            case R.id.newjob_save://保存
                if(TextUtils.isEmpty(bullJobType.getText().toString())) {
                    Toast.makeText(BullNewJobActivity.this, "工作类型不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(TextUtils.isEmpty(jxsBull.getText().toString())) {
                    Toast.makeText(BullNewJobActivity.this, "请选择经销商", Toast.LENGTH_SHORT).show();
                    return;
                }
                if("网点拜访".equals(bullJobType.getText().toString())) {
                    if(TextUtils.isEmpty(jxsBull.getText().toString())||TextUtils.isEmpty(mdBull.getText().toString())) {
                        Toast.makeText(BullNewJobActivity.this, "请至少选择一个经销商或门店", Toast.LENGTH_SHORT).show();
                        return;
                    }

                }
                isSave = true;
                showWainting("正在定位");
                initLocation();

                break;
            case jxs_bull://经销商
                if (haveJxs) {
                    changeDialog.show();
                    changeDialog.setDataJXS(listJxs);
                } else {
                    makeTureDialog.show();
                    makeTureDialog.setTitle("没有适合的经销商");
                }
                break;
            case md_bull://门店
                BeauEventList.BullMenDianEvent event = new BeauEventList.BullMenDianEvent();//查询门店
                bullDao.BullgetMenD("mendian", "dyjxs='" + jxsId + "'", "name,dzzb", event);
                break;
            case R.id.bull_job_type://工作类型
                if (haveGzlx) {
                    changeDialog.show();
                    changeDialog.setDataGZJL(listGzjl);
                } else {
                    makeTureDialog.show();
                    makeTureDialog.setTitle("无工作类型");
                }
                break;
            case R.id.image1_bull://图片1
                takePhoto(TAKE_PHOTO_1);
                break;
            case R.id.image2_bull://图片2
                takePhoto(TAKE_PHOTO_2);
                break;
            case R.id.start_time:
                // 弹出
                DateTimeUtil.initSelectTimePopuwindow(mContext,
                        starttime, false);
                break;
            case R.id.end_time:
                // 弹出
                DateTimeUtil.initSelectTimePopuwindow(mContext,
                        endtime, false);
                break;
        }
    }
    public void setTimeStr() {

        Calendar starts = Calendar.getInstance();
        int crrentHour = starts.get(Calendar.HOUR);
//        if(!"".equals(mDatime)) {
//
//        }
//            starts.setTime(DateUtils.stringToDate(mDatime, "yyyy-MM-dd HH:mm:ss"));
//            starts.set(Calendar.HOUR, crrentHour);
        starts.set(Calendar.MINUTE, 0);
        starts.set(Calendar.SECOND, 0);
        starts.add(Calendar.HOUR, 1);
        starttime.setText(DateUtils.dateToString(starts.getTime(),
                "yyyy-MM-dd HH:mm:ss"));
        starts.add(Calendar.HOUR, 1);
        endtime.setText(DateUtils.dateToString(starts.getTime(),
                "yyyy-MM-dd HH:mm:ss"));

    }
    @Override
    protected void onDestroy() {
        LocationManager.getInstance().unregisterlistener(mListener);
        unRegister();
        super.onDestroy();
    }

    private void refreshTvAddress() {
        if (null != lastDBLocation) {
            bullAddressTv.setText(LocationManager.getDetailAddr(lastDBLocation,
                    false));
        } else {
            if ("en".equals(mEns)) {
                bullAddressTv.setText("Is positioning.....");
            } else {
                bullAddressTv.setText("正在定位.....");
            }

        }
    }

    private BDLocation lastDBLocation;
    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location
                    && location.getLocType() != BDLocation.TypeServerError) {
                if ("4.9E-324".equals(String.valueOf(location.getLatitude()))) {
                    if ("en".equals(mEns)) {
                        showToast("The location failed. Check that the location permission is open");
                    } else {
                        showToast("定位失败，请查看位置权限是否打开");
                    }
                    LocationManager.getInstance().stopRequestLocal();
                }
                lastDBLocation = location;
                LocationManager.getInstance().stopRequestLocal();
                LocationManager.log(lastDBLocation);
                refreshTvAddress();
                //前面是经度 后面是纬度
                zuobiao = location.getLongitude()+","+location.getLatitude();
                if(isSave) {
                    dismissWainting();
                    mapList();
                    sendDate();
                }

            } else {
                if (null != location) {
                    if ("en".equals(mEns)) {
                        showToast("Location failed, please try again!:" + location.getLocType());
                    } else {
                        showToast("定位失败，请重试! 错误码:" + location.getLocType());
                    }

                }
            }
        }
    };

    @Override
    public void changeJxs(String names , String jxsId) {
        jxsBull.setText(names);
        this.jxsId = jxsId;
    }

    @Override
    public void changeMd(String names,String id) {
        mdBull.setText(names);
        mdid = id;
    }

    @Override
    public void changeGzlx(String names) {
        bullJobType.setText(names);
    }

    // 把数据转换成json格式。用于上传服务端
    private void mapList() {
        jsonlist = new HashMap<String,String>();
//        zcmc_bull.setText(data.zcmc);
//        zclx_bull.setText(data.zclx);

        jsonlist.put("jxs",jxsId);
        jsonlist.put("md",mdid);
        jsonlist.put("qkms",qkmsBull.getText().toString());
        jsonlist.put("gzlx", bullJobType.getText().toString());
        jsonlist.put("czsj",starttime.getText().toString());
        jsonlist.put("wwzb",zuobiao);
        jsonlist.put("dd",bullAddressTv.getText().toString());
        jsonlist.put("sj",starttime.getText().toString());
        jsonlist.put("jssj",endtime.getText().toString());
//        jsonlist.put("dymendian",data.ssmendianccname);
//        jsonlist.put("czdd",data.tfdz);
//        jsonlist.put("name",data.name);
        //营销资产id
//        jsonlist.put("yxzc",data.recordtype);
        System.out.println(jsonlist);
    }

    private void sendDate() {
        if ("en".equals(mEns)) {
            showWainting("Uploading image...");
        } else {
            showWainting("正在上传图片...");
        }

        if(imageArray.size()>0) {
            imageArrayAll.add(imageArray.get(0));
        }
        if(imageArray2.size()>0) {
            imageArrayAll.add(imageArray2.get(0));
        }
        if(imageArrayAll.size()<1) {
            Toast.makeText(BullNewJobActivity.this, "图片数量不能少于1", Toast.LENGTH_SHORT).show();
            dismissWainting();
            return;
        }

        dynamicControl.sendPhotoBull(imageArrayAll, jsonlist,isxunjian);
    }
    public void onEventMainThread(DynamicEventList.SendDynamicEvent event) {
        dismissWainting();
        if (event.isError()) {
            if (event.getStatusCode() == BaseEvent.SC_LOGIN_INVAILED) {// 登录失效
                Intent intent = new Intent(mContext, BindActivity.class);
                mContext.startActivity(intent);
            } else if (event.getStatusCode() == BaseEvent.NET_NO_NETWORK) {// 没有网络
                if ("en".equals(mEns)) {
                    Tools.showInfo(mContext, "No network yet...");
                }else{
                    Tools.showInfo(mContext, "暂无网络...");
                }

            } else if(event.getMessage()!=null) {
                String rtunrninfo =   event.getMessage();
                Toast.makeText(mContext, rtunrninfo.substring(rtunrninfo.indexOf("：")+1,rtunrninfo.length()), Toast.LENGTH_LONG).show();

            }else {
                if ("en".equals(mEns)) {
                    Tools.showInfo(mContext, "Posted  failure");
                }else{
                    Tools.showInfo(mContext, "发布失败");
                }

                finish();
            }
            return;
        }
        RunTimeManager.getInstance().setGongniu("jilu");
        finish();

    }
    public void takePhoto(int photo){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Environment.getExternalStorageDirectory() + "/"
                    + "CloudCC/photo/");
            if (!dir.exists())
                dir.mkdirs();
            imagename = Tools.getTimeName(System.currentTimeMillis());
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(dir, imagename);// localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent,photo);
        } else {
            Tools.showInfo(mContext, "请插入SD卡");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == TAKE_PHOTO_1) {

            File f = new File(Environment.getExternalStorageDirectory()
                    + "/" + "CloudCC" + "/photo/" + imagename);
            try {

                Uri u = Uri.parse(MediaStore.Images.Media
                        .insertImage(getContentResolver(),
                                f.getAbsolutePath(), null, null));
                String imageurl = getAbsoluteImagePathx(u);

                AddImageInfo imageInfo = new AddImageInfo();
                imageInfo.setImagePath(shuiyin(imageurl));
                imageArray.add(imageInfo);
                setPhotos();
            } catch (FileNotFoundException e) {
                Tools.handle(e);
            }
        }else if(requestCode == TAKE_PHOTO_2) {
            File f = new File(Environment.getExternalStorageDirectory()
                    + "/" + "CloudCC" + "/photo/" + imagename);
            try {
                Uri u = Uri.parse(MediaStore.Images.Media
                        .insertImage(getContentResolver(),
                                f.getAbsolutePath(), null, null));
                String imageurl = getAbsoluteImagePathx(u);
                shuiyin(imageurl);
                AddImageInfo imageInfo = new AddImageInfo();
                imageInfo.setImagePath(shuiyin(imageurl));
                imageArray2.add(imageInfo);
                setPhotos2();
            } catch (FileNotFoundException e) {
                Tools.handle(e);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private String shuiyin(String imageurl) {
        // 将图片加上水印
        Bitmap sourBitmap = ImageUtil.getDiskBitmap(imageurl);
        String name = "By"
                + UserManager.getManager().getUser().userName;
        String time = Tools.getTime2(System.currentTimeMillis());

//                String address = currentLoc.getAddress();
        String address = bullAddressTv.getText().toString();
        // Bitmap fugai =
        // BitmapFactory.decodeResource(getResources(), R.id.a);
        String address1 = null;
        String address2 = null;
        Bitmap textBitmap = ImageUtil.drawTextToLeftBottom(this,
                sourBitmap, name, 100, Color.WHITE, 20, 130);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, time, 100, Color.WHITE, 20, 100);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, "", 40, Color.WHITE, 20, 85);
        if (address.length() > 20) {
            address1 = address.substring(0, 20);
            address2 = address.substring(11, address.length());
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address1, 100, Color.WHITE, 20, 70);
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address2, 100, Color.WHITE, 20, 40);

        } else {
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address, 100, Color.WHITE, 20, 30);
        }

        // 存储图片
        savePhotoToSDCard(Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo", imagename + ".jpg",
                textBitmap);

        imageurl = Environment.getExternalStorageDirectory() + "/"
                + "CloudCC" + "/photo/" + imagename + ".jpg";
    return imageurl;
    }

    public String getAbsoluteImagePathx(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void setPhotos2() {
        List<String> selectedImagePathArray = AppContext.selectPhotos;
        if (imageArray2.size() + selectedImagePathArray.size() > 9) {
            selectedImagePathArray.clear();
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Add up to 9 images");
            } else {
                Tools.showInfo(mContext, "最多添加9张图片");
            }

            return;
        }
        for (String imagePath : selectedImagePathArray) {
            if (imageArray2.contains(imagePath)) {// 去重
                continue;
            }
            AddImageInfo imageInfo = new AddImageInfo();

            imageInfo.setImagePath(imagePath);
            imageArray2.add(imageInfo);
        }
        AddImageInfo localImageInfo = imageArray2.get(0);
//        adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
//        containerGridViewPhoto.setAdapter(adapter);
//        setAdapterListener();
        ImageLoader.getInstance().displayImage("file://" + localImageInfo.getImagePath(), image2Bull,
                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
        selectedImagePathArray.clear();
    }

    /**
     * 设置选中的 图片
     */
    private void setPhotos() {
        List<String> selectedImagePathArray = AppContext.selectPhotos;
        if (imageArray.size() + selectedImagePathArray.size() > 9) {
            selectedImagePathArray.clear();
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Add up to 9 images");
            } else {
                Tools.showInfo(mContext, "最多添加9张图片");
            }

            return;
        }
        for (String imagePath : selectedImagePathArray) {
            if (imageArray.contains(imagePath)) {// 去重
                continue;
            }
            AddImageInfo imageInfo = new AddImageInfo();

            imageInfo.setImagePath(imagePath);
            imageArray.add(imageInfo);
        }
        AddImageInfo localImageInfo = imageArray.get(0);
//        adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
//        containerGridViewPhoto.setAdapter(adapter);
//        setAdapterListener();
        ImageLoader.getInstance().displayImage("file://" + localImageInfo.getImagePath(), image1Bull,
                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
        selectedImagePathArray.clear();
    }
    public void savePhotoToSDCard(String path, String photoname, Bitmap pBitmap) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(path);
                if (!dir.exists())
                    dir.mkdirs();
                File photoFile = new File(path, photoname);
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(photoFile);
                    if (pBitmap != null) {
                        if (pBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                                fileOutputStream)) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        }
    }
}
